import config from '@/config'

/**
 * 弹框
 * @param {String} title
 * @param {String} icon
 * @param {Number} duration
 */
export const showToast = function (title, { icon = 'none', duration = 2000, mask = false }) {
  if (!title) return false
  return uni.showToast({ title, icon, duration })
}

/**
 * 解码
 * @param {String} data
 * @returns {String}
 */
export const decode = function (data) {
  return JSON.parse(decodeURIComponent(data))
}

/**
 * 编码
 * @param {String} data
 * @returns {String}
 */
export const encode = function (data) {
  return encodeURIComponent(JSON.stringify(data))
}

/**
 * 返回前几页，如页面栈中没有这么多页，返回可能失败，默认页数1页
 * @param {Number} delta
 */
export const navigateBack = function (delta = 1) {
  return uni.navigateBack({ delta: delta })
}

/**
 * 跳转tab页面
 * @param {String} url
 */
export const switchTab = function (url) {
  return uni.switchTab({ url })
}

/**
 * 重定向页面
 * @param {String} url
 */
export const redirectTo = function (url) {
  return uni.redirectTo({ url })
}

/**
 * 跳转页面
 * @param {String} url
 */
export const navigateTo = function (url) {
  return uni.navigateTo({ url })
}

/**
 * 预览图片
 * @param {String} current
 * @param {Array} urls
 */
export const viewImg = function (current, urls) {
  if (!urls) {
    urls = [current]
  }
  uni.previewImage({ current, urls })
}

/**
 *  打开文件
 * @param {String} fileUrl
 */
export const openFile = function (fileUrl) {
  uni.downloadFile({
    url: fileUrl,
    success: res => {
      const filePath = res.tempFilePath
      uni.openDocument({
        filePath: filePath,
        success: resp => {
          console.log('打开文档成功')
        },
        fail: err => {
          console.log(err.errMsg)
        }
      })
    }
  })
}

/**
 *  选择图片
 * @param {Number} num
 * @param {Array} sourceType
 * @param {String} sourceType
 * @returns {Promise}
 */
export const chooseImage = function (num, sourceType) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: num ? num : 9,
      sizeType: ['original', 'compressed'],
      sourceType: sourceType ? sourceType : ['album', 'camera'],
      success: res => {
        uni.showLoading()
        if (res.tempFiles[0].size / 1024 > 512) {
          imgCompress(res.tempFilePaths).then(path => {
            uni.hideLoading()
            resolve({ path })
          })
        } else {
          imgUpload(res.tempFilePaths).then(resp => {
            uni.hideLoading()
            resolve(resp)
          })
        }
      }
    })
  })
}

/**
 *  压缩图片
 * @param {Array} tempFilePaths
 * @returns {Promise}
 */
export const imgCompress = function (tempFilePaths) {
  let compressImgs = []
  tempFilePaths.forEach((src, index) => {
    compressImgs.push(
      new Promise((resolve, reject) => {
        uni.compressImage({
          src,
          quality: 60, // 仅对jpg有效
          success: res => {
            resolve(res.tempFilePath)
          },
          fail: err => {
            reject(err)
          }
        })
      })
    )
  })
  return new Promise((resolve, reject) => {
    Promise.all(compressImgs)
      .then(results => {
        imgUpload(results).then(res => {
          resolve(res)
        })
      })
      .catch(res => {
        reject(res)
      })
  })
}

/**
 * 图片上传
 * @param {Array} tempFilePaths
 * @returns {Promise}
 */
export const imgUpload = function (tempFilePaths) {
  const promiseImgList = []
  let myBaseUrl // 接口地址
  // #ifdef H5
  myBaseUrl = '/frontApi/upload'
  // #endif
  // #ifndef H5
  myBaseUrl = config.baseUrl + '/frontApi/upload'
  // #endif
  tempFilePaths.forEach((item, index) => {
    const prom = new Promise((resolve, reject) => {
      uni.uploadFile({
        url: myBaseUrl,
        filePath: item,
        name: 'file',
        header: { token: JSON.parse(wx.getStorageSync('token')) },
        formData: { user: 'test' },
        success: res => {
          console.log(res)
          resolve(JSON.parse(res.data).data)
        },
        fail: err => {
          reject(err)
        }
      })
    })
    promiseImgList.push(prom)
  })
  return new Promise((resolve, reject) => {
    Promise.all(promiseImgList)
      .then(results => {
        resolve(results)
      })
      .catch(res => {
        reject(res)
      })
  })
}

/**
 * 选择视频并上传
 * @returns {Promise}
 */
export const chooseVideo = async function () {
  uni.showLoading({
    mask: true,
    title: '上传中...'
  })
  let uploadFile = ''
  const res = await uni.chooseVideo({
    maxDuration: 60,
    sourceType: ['album', 'camera']
  })
  if (res.length == 1 && res[0].errMsg === 'chooseVideo:fail cancel') {
    uni.hideLoading()
    return
  }
  uploadFile = res[1].tempFilePath
  let myBaseUrl // 接口地址
  // #ifdef H5
  myBaseUrl = '/blade-resource/oss/endpoint/put-file-attach'
  // #endif
  // #ifndef H5
  myBaseUrl = config.baseUrl + '/blade-resource/oss/endpoint/put-file-attach'
  // #endif
  const arr = await uni.uploadFile({
    url: myBaseUrl,
    filePath: uploadFile,
    name: 'file',
    header: {
      'julian-w-token': wx.getStorageSync('julian-w-token')
    }
  })
  let data = JSON.parse(arr[1].data)
  if (data.code !== 200) {
    uni.hideLoading()
    showToast(data.msg)
    return
  }
  uni.hideLoading()
  return new Promise((resolve, reject) => {
    Promise.all([data.data])
      .then(results => {
        resolve(results)
      })
      .catch(res => {
        reject(res)
      })
  })
}

/**
 * @description: 模板消息提醒
 * @param {Array} tmplId 模板id
 * @param {Boolean} isClick 是否是点击事件触发
 * @return {*}
 */
export const subscribe = function (tmplId, isClick) {
  wx.getSetting({
    withSubscriptions: true, //  这里设置为true,下面才会返回mainSwitch
    success: res => {
      // 调起授权界面弹窗
      const { mainSwitch, itemSettings } = res.subscriptionsSetting
      if (mainSwitch) {
        // 用户打开了订阅消息总开关
        const valid = tmplId.findIndex(item => itemSettings[item] && itemSettings[item] !== 'accept')
        if (itemSettings !== null && valid === -1) {
          // 默认全部通过
          requestSubscribeMessage(tmplId)
        } else {
          const reject = tmplId.findIndex(item => !itemSettings[item] || itemSettings[item] === 'accept')
          if (reject === -1) {
            return console.log('默认全部不通过或者模板被禁用')
          }
          if (isClick) return requestSubscribeMessage(tmplId)
          wx.showModal({
            title: '提示',
            content: '请授权开通服务通知',
            showCancel: true,
            success: ({ confirm }) => {
              confirm && requestSubscribeMessage(tmplId)
            }
          })
        }
      } else {
        console.log('订阅消息未开启')
      }
    },
    fail: error => {
      console.log(error)
    }
  })
}

/**
 * @description: 获取小程序code
 * @param {String} provider weixin、qq、univerify
 * @return {Promise}
 */
export const getMpCode = (provider = 'weixin') => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider,
      success: res => {
        resolve(res.code)
      },
      fail() {
        uni.showToast({
          title: '微信登录失败',
          icon: 'none',
          duration: 1500,
          mask: true
        })
      }
    })
  })
}

const requestSubscribeMessage = function (tmplIds) {
  wx.requestSubscribeMessage({
    tmplIds: tmplIds,
    success() {
      console.log('接口调用成功 ') // 确认取消都会走这个回调
    },
    fail(err) {
      console.log('接口调用失败' + JSON.stringify(err))
    }
  })
}
